package com.shuyi.webhook.controller.gitlab;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.common.collect.Lists;
import com.shuyi.webhook.controller.gitlab.pipelineevent.PipelineEventRequest;
import com.shuyi.webhook.qywx.QyWxNotifyApplication;
import com.shuyi.webhook.qywx.WxCpProperties;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author yangyidian
 * @Date 2023/10/19
 * @Version 0.1.0
 **/
@Slf4j
@RestController
@RequestMapping("/gitlab/webhook")
public class GitlabWebHookController {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private QyWxNotifyApplication qyWxNotifyApplication;

    @Autowired
    private WxCpProperties wxCpProperties;


    Map<String, String> usernameAndPhone = new HashMap<>();


    @RequestMapping("/notify")
    public String message(@RequestHeader("X-Gitlab-Event") String gitlabEvent, @RequestBody String json) throws JsonProcessingException {
        log.info(json);
        if(gitlabEvent.equals("Pipeline Hook")){
            PipelineEventRequest request = objectMapper.readValue(json, PipelineEventRequest.class);
            if(request == null){
                String phone = usernameAndPhone.get(request.getUser().getUsername());
                if(StringUtils.hasText(phone)){
                    qyWxNotifyApplication.sendText("pipeline over", Collections.singletonList(phone));
                }
            }else {
                qyWxNotifyApplication.sendText(json, wxCpProperties.getWebhookConfig().getMobileList());
            }

        }
        log.info("response ok");
        return "ok";
    }

    @RequestMapping("/notify/json")
    public String message(Map<String, Object> param){
        log.info(param.toString());
        return "ok";
    }
}
